package com.msblearn.C_006;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

public class T007_Semaphore {
    //ArrayList是线程不安全的。
    List list = new ArrayList();
    static Thread t1 = null, t2 = null;

    public void add(Object o) {
        list.add(o);
    }

    public int size() {
        return list.size();
    }

    public static void main(String[] args) {
        T007_Semaphore t = new T007_Semaphore();
        Semaphore semaphore = new Semaphore(1);
        t1 = new Thread(() -> {
            try {
                semaphore.acquire();
                for (int i = 0; i < 5; i++) {
                    t.add("add" + 1);
                    System.out.println("add " + i);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }

            try {
                t2.start();
                t2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            try {
                semaphore.acquire();
                for(int i=5;i<10;i++){
                    System.out.println("add "+i);
                }
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        });

        t2 = new Thread(()->{
            try {
                semaphore.acquire();
                System.out.println("t2 end!");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        });

//        t2.start();
        t1.start();
    }
}
